<template>
	<view>
		<!-- 页签切换 -->
		<view class="tab-container">
			<view class="tab-list">
				<view
					v-for="(tab, index) in tabList"
					:key="index"
					class="tab-item"
					:class="{ active: activeTab === tab.value }"
					@click="switchTab(tab.value)"
				>
					<text class="tab-text">{{ tab.label }}</text>
				</view>
			</view>
		</view>

		<u-skeleton rows="18" title :loading="isFirstLoading"></u-skeleton>

		<!-- 未登录状态提示 -->
		<view v-if="!isLoggedIn" class="login-required">
			<view class="login-required-content">
				<image class="login-icon" src="/static/images/user.png" mode="aspectFit"></image>
				<text class="login-title">需要登录才能查看订单</text>
				<text class="login-desc">登录后可以查看您的所有订单信息</text>
				<!-- <button class="login-btn" @click="showLoginPopup">立即登录</button> -->
			</view>
		</view>

		<!-- 无数据空态（非首屏加载时才显示） -->
		<u-empty v-if="!isFirstLoading && orderList.length === 0 && isLoggedIn" :show="true" text="订单为空" mode="order" marginTop="50%"
			icon="http://cdn.uviewui.com/uview/empty/order.png"></u-empty>
		<view class="order">
			<view class="divBody" v-if="orderList.length > 0">
				<u-list @scrolltolower="scrolltolower" lowerThreshold="150">
					<u-list-item v-for="(order, index) in orderList" :key="order.id">
							<view class="item" @click="gotoDetail(order)">
							<view class="timeStatus">
								<view class="zuodingwei"></view>
								<text class="time">{{ order.orderTime }}</text>
								<view class="youdingwei">
									<text style="color: #ffffff;font-size: 24rpx;">{{ getStatus(order.status) }}</text>
									<view class="triangle"></view>
								</view>
							</view>

							<!-- 订单号展示 -->
							<view style="margin: 12rpx 0 8rpx 0; color:#666; font-size:24rpx;">订单号：{{ order.number }}</view>

							<!-- 商品列表：横向展示图片 + 信息 -->
							<view class="dishList">
								<view v-for="(d, di) in order.orderDetails" :key="d.id || di" style="display:flex; align-items:center; padding: 14rpx 0;">
									<u-image :src="d.image" width="96rpx" height="96rpx" radius="8rpx"></u-image>
									<view style="flex:1; display:flex; justify-content:space-between; align-items:center; margin-left: 16rpx;">
										<view style="color:#333; font-size:28rpx; max-width: 480rpx; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">{{ d.name }}</view>
										<view style="display:flex; align-items:center; gap:16rpx;">
											<text style="color:#999; font-size:24rpx;">x{{ d.number }}</text>
											<text style="color:#333; font-size:26rpx;">￥{{ d.amount }}</text>
										</view>
									</view>
									<view v-if="!order.orderDetails || order.orderDetails.length === 0" style="color:#999; font-size:24rpx; padding: 8rpx 0;">暂无商品明细</view>
								</view>
							</view>

							<view style="height: 1px;border-top: 1rpx  solid #efefef"></view>
							<view class="result">
								<text>共{{ order.sumNum }} 件商品,实付</text>
								<text class="price">￥{{ order.amount }}</text>
							</view>
							<view class="btn">
								<!-- 取消订单按钮 - 只有状态为2（待派送）时显示 -->
								<view v-if="order.status === 2" class="btnConfirm" @click.stop="cancelOrder(order)">取消</view>
								<!-- 确认收货按钮 - 只有状态为3（派送中）时显示 -->
								<view v-if="order.status === 3" class="btnConfirm" @click.stop="confirmOrder(order)">确认收货</view>
								<!-- 再来一单按钮 - 只有状态为4（已完成）时显示 -->
								<view v-if="order.status === 4" class="btnAgain" @click.stop="addOrderAgain(order)">再来一单</view>
							</view>
							<view class="foot"></view>
						</view>
					</u-list-item>
					<view v-if="this.paging.page * this.paging.pageSize < this.countToal">
						<u-loadmore :status="status" />
					</view>
				</u-list>
			</view>
		</view>
		<!--  -->
	</view>
</template>

<script>
	import '../../api/orderList.js';
	import regeneratorRuntime, {
		async
	} from '../../lib/runtime/runtime';
	import {
		addOrderApi,
		orderListApi,
		orderPagingApi,
		orderAgainApi,
		deleteOrderApi,
		confirmOrderApi,
		cancelOrderApi
	} from '../../api/orderList.js';
	export default {
		data() {
			return {
				countToal: 1,
				colorList: ['#909399', '#f9ae3d', '#f9ae3d', '#3c9cff', '#5ac725'],
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				isloading: false,
				loading: true,
				isFirstLoading: true,
				status: 'loadmore',
				wh: 0,
				active: 1,
				// 页签相关数据
				activeTab: 'all', // 当前选中的页签，默认全部
				tabList: [
					{ label: '全部', value: 'all' },
					{ label: '待派送', value: '2' },
					{ label: '派送中', value: '3' },
					{ label: '已完成', value: '4' },
					{ label: '已取消', value: '5' }
				],
				paging: {
					page: 1,
					pageSize: 10,
					status: '' // 订单状态筛选
				},
				orderList: [],
				loadedOrderIds: new Set(),

				show: true,
				orderId: '',
				touchT: null,
				TouchE: null,
				isLoggedIn: false, // 登录状态
				isFirstLoading: true // 是否是首次加载
			};
		},
		computed: {},
		created() {		},

		mounted() {
			const sysInfo = uni.getSystemInfoSync();
			this.wh = sysInfo.windowHeight;

			// 初始化时检查登录状态
			this.checkLoginStatus();
		},
		onShow() {
			// 检查是否已登录
			this.checkLoginStatus();
		},

		// 监听登录状态变化
		onLoad() {
			// 监听登录成功事件
			uni.$on('loginSuccess', () => {
				this.checkLoginStatus();
			});
		},

		onUnload() {
			// 移除事件监听
			uni.$off('loginSuccess');
		},
		onPullDownRefresh() {
			// 检查登录状态
			if (!this.isLoggedIn) {
				uni.stopPullDownRefresh();
				uni.$emit('showLoginPopup', {
					targetPage: '/pages/orderList/orderList'
				});
				return;
			}

			this.status = 'loadmore';
			this.paging.page = 1;
			this.orderList = [];
			this.loadedOrderIds = new Set(); // 清空已加载的订单ID

			// 保持当前页签状态
			if (this.activeTab === 'all') {
				this.paging.status = '';
			} else {
				this.paging.status = this.activeTab;
			}

			this.getList();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onReachBottom() {},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				this.isLoggedIn = !!token;

				if (!token) {
					this.show = true;
					this.orderList = [];
					this.loadedOrderIds = new Set();
					this.loading = false;
					this.isFirstLoading = false; // 设置为false
					setTimeout(() => {
						uni.$emit('showLoginPopup', { targetPage: '/pages/orderList/orderList' });
					}, 300);
					return;
				}
				this.loading = true;
				this.paging.page = 1;
				this.orderList = [];
				this.loadedOrderIds = new Set();
				this.activeTab = 'all';
				this.paging.status = '';
				this.getList();
				setTimeout(() => { this.loading = false; }, 500);
			},

			// 显示登录弹框
			showLoginPopup() {
				uni.$emit('showLoginPopup', {
					targetPage: '/pages/orderList/orderList'
				});
			},

			// 切换页签
			switchTab(tabValue) {
				// 检查登录状态
				if (!this.isLoggedIn) {
					uni.$emit('showLoginPopup', {
						targetPage: '/pages/orderList/orderList'
					});
					return;
				}

				if (this.activeTab === tabValue) return;

				this.activeTab = tabValue;

				// 重置分页数据
				this.paging.page = 1;
				this.orderList = [];
				this.loadedOrderIds = new Set(); // 清空已加载的订单ID
				this.status = 'loadmore';
				this.countToal = 1;
				this.isFirstLoading = true; // 重置骨架屏状态

				// 设置状态筛选
				if (tabValue === 'all') {
					this.paging.status = '';
				} else {
					this.paging.status = tabValue;
				}

				// 重新加载数据
				this.loading = true;
				this.getList();
			},

			scrolltolower() {
				if (!this.isLoggedIn) {
					uni.$emit('showLoginPopup', { targetPage: '/pages/orderList/orderList' });
					return;
				}
				if (this.isloading || this.status === 'nomore') return;
				if (this.orderList.length >= this.countToal) {
					this.status = 'nomore';
					return;
				}
				this.status = 'loading';
				this.paging.status = this.activeTab === 'all' ? '' : this.activeTab;
				this.getList();
			},

			initData() {
				this.getList();
			},

			async getList() {
				if (!this.isLoggedIn) {
					this.show = true;
					this.orderList = [];
					this.loading = false;
					this.isloading = false;
					this.isFirstLoading = false;
					return;
				}
				if (this.isloading) return;
				this.isloading = true;
				try {
					const res = await orderPagingApi(this.paging);
					if (res.code === 0) {
						const records = Array.isArray(res.data?.list) ? res.data.list : [];
						this.countToal = res.data.total || this.countToal;
						// 预处理计算sumNum
						for (const item of records) {
							let number = 0;
							(item.orderDetails || []).forEach(ele => { number += ele.number; });
							item.sumNum = number;
						}
						// 批量去重：基于Set过滤新数据，再一次性concat
						const newOnes = [];
						for (const item of records) {
							const id = item.id;
							if (id == null) continue;
							if (!this.loadedOrderIds.has(id)) {
								this.loadedOrderIds.add(id);
								newOnes.push(item);
							}
						}
						if (newOnes.length) {
							this.orderList = this.orderList.concat(newOnes);
						}
						if (this.orderList.length >= this.countToal) {
							this.status = 'nomore';
						}
						this.paging.page = this.paging.page + 1;
						this.isFirstLoading = false;
					} else {
						uni.$showMsg(res.msg || '获取订单列表失败');
					}
				} catch (error) {
					console.error('获取订单列表失败:', error);
					uni.$showMsg('获取订单列表失败，请重试');
				} finally {
					this.isloading = false;
					if (this.loading) {
						setTimeout(() => { this.loading = false; }, 500);
					}
				}
			},
			onRefresh() {
				// 清空列表数据
				console.log('正在刷新');
				this.finished = false;

				// 重新加载数据
				// 将 loading 设置为 true，表示处于加载状态
				this.loading = true;
				console.log('正在调用onload');
				this.onLoad();
			},
			async addOrderAgain(order) {
				const res = await orderAgainApi({
					id: order.id
				});
				if (res.code === 0) {
					uni.switchTab({
						url: '/pages/index/index'
					});
				} else {
					return uni.$showMsg(res.msg);
				}
			},
			beforeClose({
				position,
				instance
			}) {
				switch (position) {
					case 'left':
					case 'cell':
					case 'outside':
						instance.close();
						break;
					case 'right':
						instance.close();

						//this.deleteOrder();
						break;
				}
			},
			deleteOrder(id) {
				this.$dialog
					.confirm({
						title: '确认删除',
						message: '确认要删除当前订单吗？'
					})
					.then(() => {
						deleteOrderApi(id)
							.then(res => {
								if (res.code === 0) {
									this.getList();
									console.log('删除成功!正在调用onload');
									this.$notify({
										type: 'success',
										message: '删除成功'
									});
								} else {
									this.$notify({
										type: 'warning',
										message: res.msg
									});
								}
							})
							.catch(err => {
								this.$notify({
									type: 'danger',
									message: err
								});
							})
							.finally(() => {
								console.log('进入finally');
								this.refreshing = true;
								this.onRefresh();
							});
					});
			},
			// 确认收货
			async confirmOrder(order) {
				// 添加参数验证
				if (!order || !order.id) {
					console.error('确认收货失败: order参数无效', order);
					uni.showToast({
						icon: 'error',
						title: '订单信息无效，请重试'
					});
					return;
				}

				try {
					// 显示确认对话框
					const [error, res] = await uni.showModal({
						title: '确认收货',
						content: '确认已收到商品吗？',
						confirmText: '确认',
						cancelText: '取消'
					});

					if (error || !res.confirm) {
						return;
					}

					// 显示加载提示
					uni.showLoading({
						title: '处理中...'
					});

					// 调用确认收货接口
					const result = await confirmOrderApi(order.id);

					if (result.code === 0) {
						uni.showToast({
							icon: 'success',
							title: '确认收货成功'
						});

						// 刷新订单列表
						this.refreshOrderList();
					} else {
						uni.showToast({
							icon: 'error',
							title: result.msg || '确认收货失败'
						});
					}
				} catch (error) {
					console.error('确认收货失败:', error);
					uni.showToast({
						icon: 'error',
						title: '网络错误，请重试'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 刷新订单列表
			refreshOrderList() {
				this.paging.page = 1;
				this.orderList = [];
				this.loadedOrderIds = new Set();
				this.status = 'loadmore';
				this.countToal = 1;
				this.loading = true;
				this.isFirstLoading = true; // 重置骨架屏状态
				this.getList();
			},

			// 取消订单
			async cancelOrder(order) {
        // 添加参数验证
        if (!order || !order.id) {
          console.error('取消订单失败: order参数无效', order);
          uni.showToast({
            icon: 'error',
            title: '订单信息无效，请重试'
          });
          return;
        }
				try {
					const [err, res] = await uni.showModal({
						title: '取消订单',
						content: '确定要取消该订单吗？',
						confirmText: '取消订单',
						cancelText: '返回'
					});
					if (err || !res.confirm) return;
					uni.showLoading({ title: '处理中...' });
					const result = await cancelOrderApi(order.id);
					if (result.code === 0) {
						uni.showToast({ icon: 'success', title: '已取消' });
						this.refreshOrderList();
					} else {
						uni.showToast({ icon: 'error', title: result.msg || '取消失败' });
					}
				} catch (e) {
					console.error('取消订单失败:', e);
					uni.showToast({ icon: 'error', title: '网络错误，请重试' });
				} finally {
					uni.hideLoading();
				}
			},

			// 新增方法：根据订单ID取消订单
			async cancelOrderById(orderId) {
        console.log('取消订单ID:', orderId);
				await this.cancelOrder({ id: orderId });
			},

			getStatus(status) {
				let str = '';
				switch (status) {
					case 1:
						str = '待付款';
						break;
					case 2:
						str = '待派送';
						break;
					case 3:
						str = '派送中';
						break;
					case 4:
						str = '已完成';
						break;
					case 5:
						str = '已取消';
						break;
				}
				return str;
			},
			gotoDetail(item) {

				uni.setStorageSync('item', item)
				uni.navigateTo({
					url: '/subpkg/pages/orderDetail/orderDetail'
				})
			},
			touchstartE() {
				this.touchT = new Date().getTime();
			},
			touchendE(item) {
				const _this = this
				this.touchE = new Date().getTime();
				if (this.touchE - this.touchT < 350) {
					this.gotoDetail(item)
				} else {
					uni.showModal({
						title: '是否删除订单',
						content: '删除订单将无法查看记录',
						success: function(res) {
							console.log('1')
							if (res.confirm) {
								_this.orderList = _this.orderList.filter((i => {
									if (i.id != item.id)
										return i
								}))

							} else if (res.cancel) {
								console.log('用户点击取消');
							}
			 		}
					});
				}

			},



		}
	};
</script>

<style>
	@import url(./orderList.css);
</style>
